package cn.com.ddapp.ddm;

import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;

import com.zhy.http.okhttp.cookie.store.PersistentCookieStore;

import org.apache.commons.httpclient.HttpClient;

import java.io.File;
import java.util.Properties;
import java.util.UUID;

import cn.com.ddapp.ddm.base.BaseApplication;
import cn.com.ddapp.ddm.util.MethodsCompat;
import cn.com.ddapp.ddm.util.StringUtils;


/**
 * 全局应用程序类：用于保存和调用全局应用配置及访问网络数据
 * 
 * @version 1.0
 */
public class AppContext extends BaseApplication {

	public static final int PAGE_SIZE = 5;// 默认分页大小  
	private static AppContext instance;
	private int loginUid;
	private boolean login;
	public boolean authorize;
	public static final String KEY_FRITST_START = "KEY_FRIST_START";
	public int top;
	public boolean isStar=false;
	public boolean isPlay=true;
	@Override
	public void onCreate() {
		super.onCreate();
		instance = this;
		init();
		isPlay=true;
	}
	private void init() {
		// 初始化网络请求
		HttpClient client = new HttpClient();
		PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
//		client.setCookieStore(myCookieStore);
//		ApiHttpClient.setHttpClient(client);
//		ApiHttpClient.setCookie(ApiHttpClient.getCookie(this));
//		ImageLoaderUtil.instance();
	}




	/**
	 * 清除登录信息
	 */
	public static AppContext getInstance() {
		return instance;
	}

	public boolean containsProperty(String key) {
		Properties props = getProperties();
		return props.containsKey(key);
	}

	public void setProperties(Properties ps) {
		AppConfig.getAppConfig(this).set(ps);
	}

	public Properties getProperties() {
		return AppConfig.getAppConfig(this).get();
	}

	public void setProperty(String key, String value) {
		AppConfig.getAppConfig(this).set(key, value);
	}

	/**
	 * 获取cookie时传AppConfig.CONF_COOKIE
	 * 
	 * @param key
	 * @return
	 */
	public String getProperty(String key) {
		String res = AppConfig.getAppConfig(this).get(key);
		return res;
	}

	public void removeProperty(String... key) {
		AppConfig.getAppConfig(this).remove(key);
	}

	/**
	 * 获取App安装包信息
	 * 
	 * @return
	 */
	public PackageInfo getPackageInfo() {
		PackageInfo info = null;
		try {
			info = getPackageManager().getPackageInfo(getPackageName(), 0);
		} catch (NameNotFoundException e) {
			e.printStackTrace(System.err);
		}
		if (info == null)
			info = new PackageInfo();
		return info;
	}

	/**
	 * 获取App唯一标识
	 * 
	 * @return
	 */
	public String getAppId() {
		String uniqueID = getProperty(AppConfig.CONF_APP_UNIQUEID);
		if (StringUtils.isEmpty(uniqueID)) {
			uniqueID = UUID.randomUUID().toString();
			setProperty(AppConfig.CONF_APP_UNIQUEID, uniqueID);
		}
		return uniqueID;
	}

	public static boolean isFristStart() {
		return getPreferences().getBoolean(KEY_FRITST_START, true);
	}

	public static void setFristStart(boolean frist) {
		set(KEY_FRITST_START, frist);
	}
	
	/**
	 * 判断当前版本是否兼容目标版本的方法
	 * 
	 * @param VersionCode
	 * @return
	 */
	public static boolean isMethodsCompat(int VersionCode) {
		int currentVersion = android.os.Build.VERSION.SDK_INT;
		return currentVersion >= VersionCode;
	}
	
	/**
	 * 清除app缓存
	 */
	public void clearAppCache() {
//		// 清除webview缓存
//		 File file = CacheManager.getCacheFileBaseDir();
//		 if (file != null && file.exists() && file.isDirectory()) {
//		 for (File item : file.listFiles()) {
//		 item.delete();
//		 }
//		 file.delete();
//		 }
		deleteDatabase("webview.db");
		deleteDatabase("webview.db-shm");
		deleteDatabase("webview.db-wal");
		deleteDatabase("webviewCache.db");
		deleteDatabase("webviewCache.db-shm");
		deleteDatabase("webviewCache.db-wal");
		// 清除数据缓存
		clearCacheFolder(getFilesDir(), System.currentTimeMillis());
		clearCacheFolder(getCacheDir(), System.currentTimeMillis());
		// 2.2版本才有将应用缓存转移到sd卡的功能
		if (isMethodsCompat(android.os.Build.VERSION_CODES.FROYO)) {
			clearCacheFolder(MethodsCompat.getExternalCacheDir(this),
					System.currentTimeMillis());
		}
		// 清除编辑器保存的临时内容
		Properties props = getProperties();
		for (Object key : props.keySet()) {
			String _key = key.toString();
			if (_key.startsWith("temp"))
				removeProperty(_key);
		}
	}
	
	
	/**
	 * 清除缓存目录
	 * 
	 * @param dir
	 *            目录
	 *            当前系统时间
	 * @return
	 */
	private int clearCacheFolder(File dir, long curTime) {
		int deletedFiles = 0;
		if (dir != null && dir.isDirectory()) {
			try {
				for (File child : dir.listFiles()) {
					if (child.isDirectory()) {
						deletedFiles += clearCacheFolder(child, curTime);
					}
					if (child.lastModified() < curTime) {
						if (child.delete()) {
							deletedFiles++;
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return deletedFiles;
	}
}
